﻿
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace TcpAsyncClient
{
    sealed class RandomStringGenerator : IEnumerable<string>
    {
        private int m_size;
        private int m_interval;
        private int m_maxCount;

        public RandomStringGenerator(int size, int interval, int maxCount)
        {
            m_size = size;
            m_interval = interval;
            m_maxCount = maxCount;
        }

        public IEnumerator<string> GetEnumerator()
        {
            for (int i = 0; i < m_maxCount; ++i)
            {
                yield return ProduceRandomString();
                Thread.Sleep(m_interval);
            }
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }

        private string ProduceRandomString()
        {
            char[] charArray = new char[m_size];
            Random random = new Random();
            for (int i = 0; i < m_size; i++)
            {
                charArray[i] = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
            }
            return new string(charArray);
        } 
    }

    class Program
    {
        static IEnumerable<string> ConsoleReader()
        {
            while (true)
                yield return Console.ReadLine();
        }

        static void OnReceivedCallback(object source, ReceivedEvtArgs evtargs)
        {
            string recvMsg = Encoding.ASCII.GetString(evtargs.RecvBuffer, 0, evtargs.RecvLengthh);
            Console.WriteLine("[echo back]: {0}", recvMsg);
        }

        static void OnClosedCallback(object source, EventArgs evtargs)
        {
            Console.WriteLine("!!! connection with the server is closed.!!!\nProgram exits");
            Environment.Exit(0);
        }

        static void Main(string[] args)
        {
            using (TcpClient client = new TcpClient())
            {
                // client.Content = ConsoleReader();
                client.Content = new RandomStringGenerator(60,100,1000);

                client.ReceivedEvtHandler += OnReceivedCallback;
                client.ClosedEvtHandler += OnClosedCallback;
                client.Run("localhost", 6001);
            }
        }
    }
}
